package com.lagou.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BioServer {

    public static void main(String[] args) throws IOException {
        // 新建线程池
        ExecutorService threadPool = Executors.newCachedThreadPool();

        // 服务端监听端口
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动成功， 监听端口 6666 ..... ");
        while (true) {
            System.out.println("waiting .... ");
            Socket accept = serverSocket.accept();
            threadPool.submit(() -> {
                socketHandler(accept);
            });
        }

    }

    private static void socketHandler(Socket accept) {
        System.out.println("线程ID" + Thread.currentThread().getId() + "---线程名称----" +
                Thread.currentThread().getName());
        try (InputStream inputStream = accept.getInputStream()) {
            byte[] bytes = new byte[1024];
            while (true) {
                System.out.println("线程ID" + Thread.currentThread().getId() + "---线程名称----" +
                        Thread.currentThread().getName());
                System.out.println("reading .... ");
                int read = inputStream.read(bytes);
                if (read != -1) {
                    System.out.println(new String(bytes, 0, read));
                } else {
                    break;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                accept.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
